﻿using System;
using System.Globalization;
using System.Windows.Data;
using DataLayer.Types;

namespace ViewModel.Aggregators
{
    /// <summary>
    /// this aggregator calculates the period payment amount based on the principle , frequency and period.
    /// </summary>
    public class PaymentPeriodAggregator : IMultiValueConverter
    {

        #region IMultiValueConverter Members

        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            try
            {
                decimal val1 = System.Convert.ToDecimal(values[0]);         //principle 
                decimal val2 = System.Convert.ToDecimal(values[1]);         //scalar
                FrequencyItem frequencyItem = values[2] as FrequencyItem;   //period
                if (frequencyItem == null) return string.Empty;
                decimal val3 = System.Convert.ToDecimal(frequencyItem.ValuePerYear);

                return AggregateTools.CalculateBudgetItemPeriodPayment(val1, val2, val3).ToString("C");
            }
            catch (InvalidCastException e)
            {
                log4net.LogManager.GetLogger(GetType()).Error("Could not convert properties to a decimals", e);
                return null;
            }
            catch(DivideByZeroException d1)
            {
                log4net.LogManager.GetLogger(GetType()).Error("Attempted to divide by zero. Possibly FrequencyItem value is zero", d1);
                return null;
            }
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}
